package com.payment.ktb.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.VolleyError;
import com.payment.ktb.Interface.HttpCallbackListener;
import com.payment.ktb.R;
import com.payment.ktb.constants.HttpActions;
import com.payment.ktb.constants.HttpUrls;
import com.payment.ktb.utils.AlertDialogUtils;
import com.payment.ktb.utils.HttpUtils;
import com.payment.ktb.utils.SharedPreferencesUtils;
import com.payment.ktb.utils.ToastUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by syd on 2016/6/2.
 */
public class ForgetPasswordActivity extends BaseActivity{

    private long totalTime = 62000;
    private long intervalTime = 1000;

    String phone ;
    String code ;
    String pass;
    MyCountDownTimer countDownTimer;
    @BindView(R.id.et_forgetpasswordactivity_phone)
    EditText et_forgetpasswordactivity_phone;
    @BindView(R.id.et_forgetpasswordactivity_code)
    EditText et_forgetpasswordactivity_code;
    @BindView(R.id.et_forgetpasswordactivity_pass)
    EditText et_forgetpasswordactivity_pass;
    @BindView(R.id.btn_forgetpasswordactivity_obtaincode)
    Button btn_forgetpasswordactivity_obtaincode;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgetpassword);
        ButterKnife.bind(this);
        initTitle("忘记密码");
        et_forgetpasswordactivity_pass.addTextChangedListener(textWatcher);
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getString("loginName"))) {
            et_forgetpasswordactivity_phone.setText(SharedPreferencesUtils.getString("loginName").substring(0,3) + "****" + SharedPreferencesUtils.getString("loginName").substring(7,11));
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {

        phone = et_forgetpasswordactivity_phone.getText().toString().trim();
        if (!TextUtils.isEmpty(phone) && phone.contains("*")) {
            phone = SharedPreferencesUtils.getString("loginName");
        }
        code = et_forgetpasswordactivity_code.getText().toString().trim();
        pass = et_forgetpasswordactivity_pass.getText().toString().trim();
    }


    /**
     *
     * @param view
     */
    @OnClick({R.id.btn_forgetpasswordactivity_obtaincode,R.id.btn_forgetpasswordactivity_submit,R.id.rl_forgetpassword_deletephone})
    public void clickEvent(View view) {
        switch (view.getId()) {



            //商户找回密码短信
            case R.id.btn_forgetpasswordactivity_obtaincode:
                initData();
                if (TextUtils.isEmpty(phone) || phone.length() != 11) {
                    ToastUtils.showToast("请输入正确的11位手机号码！");
                } else {
                    obtainMsgCode();
                }
                break;


            //商户找回密码提交
            case R.id.btn_forgetpasswordactivity_submit:
                initData();
                if (checkPass()) {
                    submit();
                }
                break;

            //删除手机号
            case R.id.rl_forgetpassword_deletephone:
                et_forgetpasswordactivity_phone.setText("");
                break;
        }
    }


    /**
     *检查参数输入是否完整
     */
    private boolean checkPass() {
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showToast("请输入手机号码");
            return false;
        } else if (phone.length() != 11) {
            ToastUtils.showToast("手机号码不正确");
            return false;
        }else if (TextUtils.isEmpty(code)) {
            ToastUtils.showToast("请输入验证码");
            return false;
        } else if (code.length() > 6) {
            ToastUtils.showToast("验证码位数不大于6位");
            return false;
        } else if (TextUtils.isEmpty(pass)) {
            ToastUtils.showToast("请输入密码");
            return false;
        } else if (pass.length() < 6) {
            ToastUtils.showToast("请输入6-20位密码");
            return false;
        }else {
            return true;
        }
    }

    /**
     *
     */
    private void submit() {

        progressDialogUtils.showProgress();

        //构造传输参数

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();

        map.put("phone",phone);
        map.put("code", code);
        map.put("pass", pass);
        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserFindPassState, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                progressDialogUtils.dismissProgress();
                ToastUtils.showToast("修改密码成功！");
                startActivityThenKill(LoginActivity.class);
            }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                AlertDialogUtils.showAlertDialog(mContext, volleyError.getMessage());
            }
        });

    }

    /**
     * 获取注册的短信验证码
     */
    private void obtainMsgCode() {
        countDownTimer = new MyCountDownTimer(totalTime,intervalTime);
        countDownTimer.start();
        progressDialogUtils.showProgress();

        //构造传输参数

        //将参数放入map中
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("phone",phone);

        //向服务器发送请求
        HttpUtils.HttpRequestByVollery(HttpUrls.URL, HttpActions.UserFindPassStateSms, map, mQueue, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {
                progressDialogUtils.dismissProgress();
                ToastUtils.showToast("获取验证码成功！");
                }

            @Override
            public void onError(VolleyError volleyError) {
                progressDialogUtils.dismissProgress();
                countDownTimer.cancel();
                btn_forgetpasswordactivity_obtaincode.setEnabled(true);
                btn_forgetpasswordactivity_obtaincode.setText("重新获取");
                AlertDialogUtils.showAlertDialog(mContext,volleyError.getMessage());
            }
        });


    }


    /**
     * 获取短信验证码的时候，显示倒计时
     */
    class MyCountDownTimer extends CountDownTimer {

        /**
         *
         * @param millisInFuture
         *            倒计时总时间
         * @param countDownInterval
         *            每隔多久触发onTick方法
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onFinish() {
            btn_forgetpasswordactivity_obtaincode.setText("重新获取");
            btn_forgetpasswordactivity_obtaincode.setEnabled(true);
        }

        @Override
        public void onTick(long arg0) { // arg0 表示距离本级倒计时结束还有多长时间

            btn_forgetpasswordactivity_obtaincode.setText("重新获取" + "(" + ((arg0 / 1000) -1) + ")" );
            btn_forgetpasswordactivity_obtaincode.setEnabled(false);

        }

    }




    private TextWatcher textWatcher = new TextWatcher() {


        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String etValues = s.toString().trim();

        }


    };

}
